import { history } from '@umijs/max';
import { message } from 'antd';
import Cookies from 'js-cookie';
import { stringify } from 'querystring';
import { extend } from 'umi-request';
const baseUrl = 'http://10.168.1.102:8098';
let loginToken = '';
/** 异常处理程序 */
const errorHandler = (error: any) => {
  throw error; // 抛出自制的错误
};

/** 配置request请求时的默认参数 */
const request: any = extend({
  prefix: process.env.REACT_APP_SAASBASEURL,
  errorHandler, // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
  timeout: 60000,
});

/** 配置SaaS JWT 授权Header */
request.interceptors.request.use(
  (url: string, options: any) => {
    const headers = {
      ...options.headers,
      satoken: Cookies.get('Token') || loginToken || '',
    };

    if (options?.params?.current) {
      options.params = {
        ...options.params,
        pageNum: options.params?.current || 1,
      };
      delete options.params.current;
    }

    // 在这里可以判断参数是否为空，如果为空则删除该参数
    if (options?.params) {
      Object.keys(options.params).forEach((key) => {
        if (options.params[key] === undefined || options.params[key] === '') {
          delete options.params[key];
        }
      });
    }
    const targetUrl =
      process?.env?.NODE_ENV === 'development'
        ? url
        : baseUrl + url.replace('/proxyapi', '/prod-api');

    return {
      url: targetUrl,
      options: {
        ...options,
        headers,
      },
    };
  },
  { global: false },
);

request.interceptors.response.use(
  async (response: any) => {
    const httpdata = await response.clone().json();
    const { code, data, msg } = httpdata;
    if (code === 200) {
      return httpdata;
    } else if (code === 401) {
      message.error("登录失效，请重新登录！");
      const { search, pathname } = window.location;
      const urlParams = new URL(window.location.href).searchParams;
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const redirect = urlParams.get('redirect');
      if (window.location.pathname !== '/login' && !redirect) {
        history.replace({
          pathname: '/login',
          search: stringify({
            redirect: pathname + search,
          }),
        });
        return;
      }
    } else {
      msg && message.error(msg);
      return ;
    }
  },
  { global: false },
);

export default request;
